package cn.wanho.handler;

import cn.wanho.dao.CmsUserMapper;
import cn.wanho.dto.CmsUser;
import cn.wanho.rvo.ResultEnum;
import cn.wanho.rvo.ResultVO;
import cn.wanho.util.JWTUtil;
import cn.wanho.util.JsonUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功代码的处理逻辑
 * @author qzw
 */

public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    CmsUserMapper cmsUserMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取登录用户的信息为其生成token
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CmsUser cmsUser = cmsUserMapper.selectByUsername(user.getUsername());
        String token = JWTUtil.createJWT(cmsUser , "loginUSer", null);

        ResultVO result = ResultVO.success(ResultEnum.LOGIN_SUCCESS.getResCode(), ResultEnum.LOGIN_SUCCESS.getResMsg(),token);
        response.setContentType("text/json;charset=utf8");
        response.getWriter().write(JsonUtil.toJson(result));
    }
}
